package com.banmoon.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class Demo7 {

    public static void main(String[] args) {
        MyDemo7 demo7 = new MyDemo7();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                demo7.add(Thread.currentThread().getName());
            }, "写线程" + i).start();
            new Thread(() -> {
                demo7.toString(true);
            }, "读线程" + i).start();
        }

    }

}

class MyDemo7{

    private List<String> list = new ArrayList<>();

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//    private ReentrantLock lock = new ReentrantLock();

    public void add(String str){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "：正在添加");
            list.add(str);
            System.out.println(Thread.currentThread().getName() + "：添加成功");
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void toString(boolean b){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "：正在读取");
            System.out.println(Thread.currentThread().getName() + "：" + list);
            System.out.println(Thread.currentThread().getName() + "：读取成功");
        } finally {
            lock.readLock().unlock();
        }
    }

}